﻿#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.dll"
#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.Runtime.dll"

#load "Client.fs"

open Client
open Microsoft.SharePoint.Client
open Microsoft.SharePoint.Client.Application
open System.Security;

// =======================================================
// Create and assign roles
// =======================================================

let web = Client.Context.Web
let list = Client.Context.Web.Lists.GetByTitle("Documents")
Client.Load list

// Creating a role definition

let perm = new BasePermissions()
perm.Set(PermissionKind.CreateAlerts)
perm.Set(PermissionKind.ManageAlerts)

let roleInfo = new RoleDefinitionCreationInformation()
roleInfo.BasePermissions <- perm
roleInfo.Name <- "TestRole"

// Retrieve all roles
let roles = web.RoleDefinitions
Client.Load roles

for role in roles do
    Client.Load role
    let msg =  role.Id.ToString() + " | " + role.Name
    printfn "%s\n" msg

Client.ExecuteQuery()

// Assigning a user to a role on a web site

let spUser = Client.Context.Web.SiteUsers.GetByLoginName("me@geek.onmicrosoft.com")
let oRoleDefinition = Client.Context.Web.RoleDefinitions.GetByName("TestRole");

let collRoleDefinitionBinding = new RoleDefinitionBindingCollection(Client.Context);
collRoleDefinitionBinding.Add(oRoleDefinition);
let oRoleAssignment = Client.Context.Web.RoleAssignments.Add(spUser, collRoleDefinitionBinding);
Client.ExecuteQuery()

// Creating a SharePoint group and adding the group to a role

let groupInfo = new GroupCreationInformation()
groupInfo.Title <- "TestGroup"
let newGroup = Client.Context.Web.SiteGroups.Add(groupInfo)
Client.ExecuteQuery()

let newRoleBinding = new RoleDefinitionBindingCollection(Client.Context);
newRoleBinding.Add(oRoleDefinition);
let newAssignment = Client.Context.Web.RoleAssignments.Add(newGroup, newRoleBinding);
Client.ExecuteQuery()

